//
//  SHByteUtils.m
//  Backhome
//
//  Created by kwep_vbn on 2017/3/29.
//  Copyright © 2017年 SmartHome. All rights reserved.
//

#import "KNByteUtils.h"

@implementation KNByteUtils

+ (NSString *)KNGetHexStringByData:(NSData *)data
{
    NSMutableString* mStr = [[NSMutableString alloc]init];
    NSUInteger totalLen = [data length];
    Byte bytes[totalLen];
    [data getBytes:&bytes length:totalLen];
    for (int i = 0; i < totalLen; i++)
    {
        NSString *hexString = [[NSString alloc]initWithFormat:@"%.2x",bytes[i]];
        [mStr appendString:hexString];
    }
    return mStr;
}

+ (NSData *)KNGetBytesByNSString:(NSString *)string {
    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= string.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [string substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}

+ (int)KNGetDecimalWithHexString:(NSString *)hex {
    return [[NSString stringWithFormat:@"%lu",strtoul([hex UTF8String],0,16)] intValue];
}


+ (Byte)KNConvertUint8toByte:(char) uint8
{
    return (Byte)uint8;
}

+ (UInt8)KNConvertByte2Uint8:(Byte) b
{
    return (UInt8) (b & 0xff);
}

//将十进制转化为十六进制
+ (NSString *)KNToHex:(int)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    int ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:
                nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
    }
    //不够一个字节凑0
    if(str.length == 1){
        return [NSString stringWithFormat:@"0%@",str];
    }else{
        return str;
    }
}

+ (NSString *)KNStringByHexInt:(int)hexInt {
    NSString *str = [NSString stringWithFormat:@"%X",hexInt];
    //不够一个字节凑0
    if(str.length == 1){
        return [NSString stringWithFormat:@"0%@",str];
    }else{
        return str;
    }
}

+ (int)KNHexInt2Int:(int)hexInt {
    return [[NSString stringWithFormat:@"%d",hexInt] intValue];
}

//  十进制转二进制
+ (NSString *)KNToBinarySystemWithDecimalSystem:(int)num length:(int)length
{
    int remainder = 0;      //余数
    int divisor = 0;        //除数
    
    NSString * prepare = @"";
    
    while (true)
    {
        remainder = num%2;
        divisor = num/2;
        num = divisor;
        prepare = [prepare stringByAppendingFormat:@"%d",remainder];
        
        if (divisor == 0)
        {
            break;
        }
    }
    //倒序输出
    NSString * result = @"";
    for (int i = length -1; i >= 0; i --)
    {
        if (i <= prepare.length - 1) {
            result = [result stringByAppendingFormat:@"%@",
                      [prepare substringWithRange:NSMakeRange(i , 1)]];
            
        }else{
            result = [result stringByAppendingString:@"0"];
            
        }
    }
    return result;
}

//  二进制转十进制
+ (NSString *)KNToDecimalWithBinary:(NSString *)binary {
    int ll = 0 ;
    int  temp = 0 ;
    for (int i = 0; i < binary.length; i ++)
    {
        temp = [[binary substringWithRange:NSMakeRange(i, 1)] intValue];
        temp = temp * powf(2, binary.length - i - 1);
        ll += temp;
    }
    
    NSString * result = [NSString stringWithFormat:@"%d",ll];
    
    return result;
}

/**
 二进制转换成十六进制
 
 @param binary 二进制数
 @return 十六进制数
 */
+ (NSString *)KNGetHexByBinary:(NSString *)binary {
    
    NSMutableDictionary *binaryDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    
    [binaryDic setObject:@"0" forKey:@"0000"];
    [binaryDic setObject:@"1" forKey:@"0001"];
    [binaryDic setObject:@"2" forKey:@"0010"];
    [binaryDic setObject:@"3" forKey:@"0011"];
    [binaryDic setObject:@"4" forKey:@"0100"];
    [binaryDic setObject:@"5" forKey:@"0101"];
    [binaryDic setObject:@"6" forKey:@"0110"];
    [binaryDic setObject:@"7" forKey:@"0111"];
    [binaryDic setObject:@"8" forKey:@"1000"];
    [binaryDic setObject:@"9" forKey:@"1001"];
    [binaryDic setObject:@"A" forKey:@"1010"];
    [binaryDic setObject:@"B" forKey:@"1011"];
    [binaryDic setObject:@"C" forKey:@"1100"];
    [binaryDic setObject:@"D" forKey:@"1101"];
    [binaryDic setObject:@"E" forKey:@"1110"];
    [binaryDic setObject:@"F" forKey:@"1111"];
    
    if (binary.length % 4 != 0) {
        
        NSMutableString *mStr = [[NSMutableString alloc]init];;
        for (int i = 0; i < 4 - binary.length % 4; i++) {
            
            [mStr appendString:@"0"];
        }
        binary = [mStr stringByAppendingString:binary];
    }
    
    NSString *hex = @"";
    
    for (int i=0; i<binary.length; i+=4) {
        
        NSString *key = [binary substringWithRange:NSMakeRange(i, 4)];
        hex = [hex stringByAppendingString:[binaryDic objectForKey:key]];
    }
    
    return hex;
}

/**
 十六进制转换为二进制
 
 @param hex 十六进制数
 @return 二进制数
 */
+ (NSString *)KNGetBinaryByHex:(NSString *)hex {
    
    NSMutableDictionary *hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    
    [hexDic setObject:@"0000" forKey:@"0"];
    [hexDic setObject:@"0001" forKey:@"1"];
    [hexDic setObject:@"0010" forKey:@"2"];
    [hexDic setObject:@"0011" forKey:@"3"];
    [hexDic setObject:@"0100" forKey:@"4"];
    [hexDic setObject:@"0101" forKey:@"5"];
    [hexDic setObject:@"0110" forKey:@"6"];
    [hexDic setObject:@"0111" forKey:@"7"];
    [hexDic setObject:@"1000" forKey:@"8"];
    [hexDic setObject:@"1001" forKey:@"9"];
    [hexDic setObject:@"1010" forKey:@"A"];
    [hexDic setObject:@"1011" forKey:@"B"];
    [hexDic setObject:@"1100" forKey:@"C"];
    [hexDic setObject:@"1101" forKey:@"D"];
    [hexDic setObject:@"1110" forKey:@"E"];
    [hexDic setObject:@"1111" forKey:@"F"];
    
    NSString *binary = @"";
    
    for (int i=0; i<[hex length]; i++) {
        
        NSString *key = [hex substringWithRange:NSMakeRange(i, 1)];
        binary = [binary stringByAppendingString:[hexDic objectForKey:key]];
    }
    
    return binary;
}

+ (NSString *)KNTransforLittleEndianByInt:(int)code {
    int temp = code;
    HTONS(temp);//转换
    NSString *sence_16 = [[NSString stringWithFormat:@"%4x",temp] uppercaseString];
    if ([sence_16 containsString:@" "]) {
        sence_16 = [sence_16 stringByReplacingOccurrencesOfString:@" " withString:@"0"];
    }
    return sence_16;
}

+ (int)KNDecimalLittleEndianByHexString:(NSString *)hexString {
    int decimal = [KNByteUtils KNGetDecimalWithHexString:hexString];
    NTOHS(decimal);
    return decimal;
}

+ (NSData *)KNDataFromHexString:(NSString *)hexString {
    const char *chars = [hexString UTF8String];
    int i = 0, len = hexString.length;
    
    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;
    while (i < len) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }
    return data;
}

+ (int)KNGetDecimalWithData:(NSData *)data {
    NSString *hexStr = [self KNGetHexStringByData:data];
    return [self KNGetDecimalWithHexString:hexStr];
}
@end
